import { ProFormInstance, ProFormText, ProFormRadio, StepsForm } from '@ant-design/pro-components';
import React, { useRef } from 'react';
import { Button, Modal, message, Select, TreeSelect, Table, Popconfirm } from 'antd';
import { useState, useEffect } from 'react';
import { addUser, getUserList, getUserDetail, editUser, deleteUser, updateUserStatus, resetPassword } from 'apis/user';
import { getOrgTree, getAppList, getRoleList } from 'apis/common';
import { useTokenStore } from 'store/user';

export default (props):JSX.Element => {
    // 新增弹框
    const { visible, setVisible, refresh, organization } = props;
    // 步骤
    const [current, setCurrent] = useState(0);

    const onCurrentChange = (value) => {
        console.log(value);
        setCurrent(value);
        if (value === 1) {
            console.log(formRef?.current?.getFieldValue());
        }
    };
    // 角色
    const [role, setRole] = useState(undefined);
    const [roleName, setRoleName] = useState(undefined);
    const [roleList, setRoleList] = useState([]);
    const [roleDataSource, setRoleDataSource] = useState([]);

    const roleColumns = [
        {
            title: '组织机构',
            dataIndex: 'organizationFullName',
            key: 'organizationFullName',
        },
        {
            title: '角色名字',
            dataIndex: 'roleName',
            key: 'roleName',
        },
        {
            title: '操作',
            key: 'action',
            width: 80,
            render: (_, record) => (
                <Popconfirm
                    title='删除角色'
                    description='确认删除该角色?'
                    onConfirm={() => deleteRole(record)}
                    okText='确定'
                    cancelText='取消'
                >
                    <a>删除</a>
                </Popconfirm>
            ),
        },
    ];

    const getRoleSelectList = (organizationId) => {
        getRoleList({ organizationId }).then((res) => {
            setRoleList(res.recordDatas);
        });
    };
    const deleteRole = (record) => {
        let list = roleDataSource.filter((item) => item.roleId !== record.roleId);
        setRoleDataSource(list);
        console.log(record);
    };

    const addRole = () => {
        if (!role) return message.warning('请先选择角色！');
        if (roleDataSource.filter((item) => item.roleId === role).length > 0)
            return message.warning('请不要重复添加！');
        const list = [...roleDataSource];
        list.push({
            roleName: roleName,
            roleId: role,
            organizationFullName: orgName,
            orgId: org,
        });
        setRoleDataSource(list);
    };
    // 通过应用筛选角色
    // const [appList, setAppList] = useState([]);
    // const [app, setApp] = useState(undefined);
    // 通过组织筛选角色
    const [orgTree, setOrgTree] = useState([]);
    const [org, setOrg] = useState(undefined);
    const [orgName, setOrgName] = useState(undefined);

    // 表单
    const formRef = useRef<ProFormInstance>();

    const formItemLayout = {
        labelCol: {
            span: 4,
        },
        wrapperCol: {
            span: 20,
        },
    };

    const handleCancel = () => {
        setCurrent(0);
        setRole(undefined);
        // setOrg(undefined);
        // setApp(undefined);
        setRoleDataSource([]);
        setVisible(false);
    };
    const handleSubmitOne = () => {
        formRef.current?.validateFieldsReturnFormatValue?.().then((data) => {
            console.log('校验表单并返回格式化后的所有数据：', data);
            if (organization) data.organizationId = organization.id;
            data.mobile = data.userName;
            addUser(data).then((res) => {
                setCurrent(0);
                setRole(undefined);
                // setOrg(undefined);
                // setApp(undefined);
                setRoleDataSource([]);
                setVisible(false);
                refresh();
                message.success('用户创建成功');
            });
        });
    };

    // 初始化数据
    // const { currentTenant } = useTokenStore();
    useEffect(() => {
        // getAppList({ pageSize: 9999, pageNumber: 1, validStat: 1 }).then(res => {
        // 	console.log(res);
        // 	setAppList(res.recordDatas);
        // });
        getOrgTree({}).then((res) => {
            console.log(res);
            setOrgTree([res.organizationTree]);
        });
        if (organization) {
            setOrgName(organization.name);
            setOrg(organization.id);
            getRoleSelectList(organization.id);
        }
    }, [visible]);

    return (
        <>
            <StepsForm
                onFinish={async (data) => {
                    if (organization) data.organizationId = organization.id;
                    data.roleIds = roleDataSource.map((item) => item.roleId);
                    data.mobile = data.userName;
                    addUser(data).then((res) => {
                        setCurrent(0);
                        setRole(undefined);
                        // setOrg(undefined);
                        // setApp(undefined);
                        setRoleDataSource([]);
                        setVisible(false);
                        refresh();
                        message.success('用户创建成功');
                    });
                }}
                current={current}
                onCurrentChange={onCurrentChange}
                formProps={{
                    validateMessages: {
                        required: '此项为必填项',
                    },
                }}
                submitter={{
                    render: (props) => {
                        if (props.step === 0) {
                            return (
                                <>
                                    {' '}
                                    <Button type='primary' onClick={() => props.onSubmit?.()}>
                                        下一步
                                    </Button>
                                    <Button type='primary' onClick={handleSubmitOne}>
                                        提交
                                    </Button>
                                    ,
                                </>
                            );
                        }

                        if (props.step === 1) {
                            return [
                                <Button key='pre' onClick={() => props.onPre?.()}>
                                    上一步
                                </Button>,
                                <Button type='primary' onClick={() => props.onSubmit?.()}>
                                    完成
                                </Button>,
                            ];
                        }
                    },
                }}
                stepsFormRender={(dom, submitter) => {
                    return (
                        <Modal
                            title='创建用户'
                            centered
                            zIndex={50}
                            styles={{ body: { marginTop: '40px', marginBottom: '40px' } }}
                            width={800}
                            onCancel={handleCancel}
                            open={visible}
                            footer={submitter}
                            destroyOnClose
                        >
                            {dom}
                        </Modal>
                    );
                }}
            >
                <StepsForm.StepForm
                    name='base'
                    layout='horizontal'
                    {...formItemLayout}
                    formRef={formRef}
                    title='填写基本信息'
                    onFinish={async () => {
                        // await waitTime(500);
                        console.log('第一步完成');
                        return true;
                    }}
                >
                    <ProFormText
                        name='userName'
                        label='用户名'
                        placeholder='请输入手机号'
                        rules={[
                            { required: true },
                            () => ({
                                validator(_, value) {
                                    if (!value || /1[3-9]\d{9}/.test(value)) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('用户名必须为手机号，请正确输入'));
                                },
                            }),
                        ]}
                    />
                    <ProFormText name='name' label='姓名' placeholder='请输入姓名' rules={[{ required: true }]} />
                    {/* <ProFormText
						name="mobile"
						label="手机号"
						placeholder="请输入手机号"
						rules={[
							{ required: false },
							() => ({
								validator(_, value) {
									if (!value || /1[3-9]\d{9}/.test(value)) {
										return Promise.resolve();
									}
									return Promise.reject(new Error('请输入正确的手机号码！'));
								},
							}),
						]}
					/> */}
                    <ProFormRadio.Group
                        label='性别'
                        name='sex'
                        options={[
                            { label: '男', value: 1 },
                            { label: '女', value: 2 },
                        ]}
                    />
                </StepsForm.StepForm>
                <StepsForm.StepForm name='rolePower' title='角色权限绑定'>
                    <div className='w-[640px]'>
                        <div className='flex gap-[20px]'>
                            {/* <Select
								style={{ width: '100%' }}
								placeholder="请选择应用"
								fieldNames={{ label: 'name', value: 'id' }}
								onChange={value => {
									setApp(value);
									setRole(undefined);
									if (org) {
										getRoleSelectList(value, org);
									}
								}}
								options={appList}
							/> */}
                            <TreeSelect
                                style={{ width: '100%' }}
                                dropdownStyle={{ maxHeight: 500, minWidth: 260, overflow: 'auto' }}
                                placeholder='请选择组织机构'
                                value={org}
                                treeDefaultExpandAll
                                disabled={organization ? true : false}
                                onChange={(value, label) => {
                                    if (value !== org) setRole(undefined);
                                    setOrgName(label);
                                    setOrg(value);
                                    getRoleSelectList(value);
                                }}
                                fieldNames={{ label: 'name', value: 'id' }}
                                treeData={orgTree}
                            />
                            <Select
                                style={{ width: '100%' }}
                                placeholder='请选择角色'
                                value={role}
                                fieldNames={{ label: 'name', value: 'id' }}
                                disabled={!org}
                                onChange={(value, option) => {
                                    setRole(value);
                                    setRoleName(option.name);
                                }}
                                options={roleList}
                            />
                            <Button type='primary' onClick={addRole}>
                                添加
                            </Button>
                        </div>
                        <div className='mt-[20px]'>
                            <Table columns={roleColumns} dataSource={roleDataSource} />
                        </div>
                    </div>
                </StepsForm.StepForm>
            </StepsForm>
        </>
    );
};
